using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace BusinessLibrary
{
	public delegate void CommandReceivedEventHandler(object sender, CommandEventArgs e);
	
	public class UdpCommandListener
	{
		private UdpClient udpclient = null;
		public event CommandReceivedEventHandler CommandReceived;
		public int port { get; set;}
		
		public UdpCommandListener ()
		{
			port = 8080;
		}
		
		/// <summary>
        /// 在后台运行的接收线程
        /// </summary>
        private void RecData()
        {
            //本机指定端口接收
            udpclient = new UdpClient(port);
            IPEndPoint remote = null;
            //接收从远程主机发送过来的信息
            while (true)
            {
                try
                {
                    //关闭udpclient时此句会产生异常
                    byte[] bytes = udpclient.Receive(ref remote);
                    string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
					if(CommandReceived != null)
					{
						CommandReceived(this, new CommandEventArgs(){ Command = str});
					}
                    //AppendString(string.Format("来自{0}:{1}", remote, str));
                }
                catch
                {
                    //退出循环,结束线程
                    break;
                }
            }
        }
		
	}
	
	public class CommandEventArgs : EventArgs
	{
		public string Command {get; set;}
	}
}

